<template>
  <div class="login-register-page">
    <div class="container">
      <!-- 欢迎区域 -->
      <div class="welcome-section">
        <div class="brand-logo">
          <img src="@/assets/logo1.png" alt="安恒信息">
          <span>安恒信息</span>
        </div>
        <div class="network-bg"></div>
        <div class="node node-1"></div>
        <div class="node node-2"></div>
        <div class="node node-3"></div>
        <div class="node node-4"></div>

        <div class="welcome-content">
          <h1>{{ activeForm === 'login' ? '欢迎回到攻防靶场' : '加入AI攻防演练' }}</h1>
          <p v-if="activeForm === 'login'">
            欢迎登录AI Agent驱动的动态攻防推演靶场平台，继续您的安全实战演练。平台支持动态场景生成、智能攻防模拟等核心功能。
          </p>
          <p v-else>
            注册账号，解锁动态攻防推演靶场的全部功能。支持个人或团队使用，满足攻防演练、策略验证等需求。
          </p>
          <div>
            <span class="project-tag">AI Agent技术</span>
            <span class="project-tag">动态攻防推演</span>
            <span class="project-tag">网络安全演练</span>
          </div>
        </div>
      </div>

      <!-- 表单区域 -->
      <div class="form-section">
        <div class="form-container">
          <!-- 标签切换 -->
          <div class="tabs">
            <div
                class="tab"
                :class="{ active: activeForm === 'login' }"
                @click="switchForm('login')"
            >
              登录
            </div>
            <div
                class="tab"
                :class="{ active: activeForm === 'register' }"
                @click="switchForm('register')"
            >
              注册
            </div>
          </div>

          <!-- 登录表单 -->
          <LoginForm
              v-if="activeForm === 'login'"
              :errors="loginErrors"
              @submit="handleLogin"
              @validate="validateLoginField"
          />

          <!-- 注册表单 -->
          <RegisterForm
              v-else
              :errors="registerErrors"
              @submit="handleRegister"
              @validate="validateRegisterField"
          />

          <!-- 表单错误信息显示区域 -->
          <div v-if="formErrorMessage" class="form-error-message">
            {{ formErrorMessage }}
          </div>

          <!-- 社交登录 -->
          <div class="social-login">
            <p>或使用科研平台账号登录</p>
          </div>

          <div class="social-icons">
            <div class="social-icon google">
              <i class="fab fa-google"></i>
            </div>
            <div class="social-icon gitlab">
              <i class="fab fa-gitlab"></i>
            </div>
          </div>

          <div class="form-footer">
            <p v-if="activeForm === 'login'">
              还没有账户? <a href="#" @click.prevent="switchForm('register')">立即注册</a>
            </p>
            <p v-else>
              已有账户? <a href="#" @click.prevent="switchForm('login')">立即登录</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import LoginForm from '@/components/common/LonAndRes/LoginForm.vue'
import RegisterForm from '@/components/common/LonAndRes/RegisterrForm.vue'
import LogAndRes from "@/api/common/LogAndRes.js";
import CryptoJS from 'crypto-js'

export default {
  components: {
    LoginForm,
    RegisterForm
  },
  data() {
    return {
      activeForm: 'login',
      formErrorMessage: '', // 添加表单错误信息
      // 登录相关数据
      loginFormData: {
        email: '',
        password: '',
        captcha: '',
        remember: false
      },
      loginErrors: {
        email: '',
        password: '',
        captcha: ''
      },
      // 验证码
      captchaCode: '',
      
      // 注册相关数据
      registerFormData: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      registerErrors: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  mounted() {
    // 页面加载时生成验证码
    if (this.activeForm === 'login') {
      this.generateCaptcha();
    }
  },
  methods: {
    // 生成验证码
    generateCaptcha() {
      const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
      let captcha = '';
      for (let i = 0; i < 4; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      this.captchaCode = captcha;
      // 将验证码存储到 localStorage 中，便于在登录表单组件中使用
      localStorage.setItem('loginCaptcha', captcha);
    },
    
    // 切换表单时重新生成验证码
    switchForm(formType) {
      this.activeForm = formType;
      if (formType === 'login') {
        this.generateCaptcha();
      }
    },

    // 登录字段验证
    validateLoginField(field) {
      this.loginFormData[field.name] = field.value
      switch (field.name) {
        case 'email':
          return this.validateLoginEmail(field.value)
        case 'password':
          return this.validateLoginPassword(field.value)
        case 'captcha':
          return this.validateLoginCaptcha(field.value)
      }
    },

    // 注册字段验证
    validateRegisterField(field) {
      this.registerFormData[field.name] = field.value
      switch (field.name) {
        case 'username':
          return this.validateRegisterUsername(field.value)
        case 'email':
          return this.validateRegisterEmail(field.value)
        case 'password':
          return this.validateRegisterPassword(field.value)
        case 'confirmPassword':
          return this.validateRegisterConfirmPassword(field.value)
      }
    },

    // 登录邮箱验证
    validateLoginEmail(email) {
      if (!email) {
        this.loginErrors.email = '请输入邮箱地址'
        return false
      }

      const emailRegex = /^([a-zA-Z0-9]+[-_.]?)+@[a-zA-Z0-9]+.[a-z]+$/
      if (!emailRegex.test(email)) {
        this.loginErrors.email = '请输入有效的邮箱地址'
        return false
      }

      this.loginErrors.email = ''
      return true
    },

    // 登录密码验证
    validateLoginPassword(password) {
      if (!password) {
        this.loginErrors.password = '请输入密码'
        return false
      }

      this.loginErrors.password = ''
      return true
    },

    // 登录验证码验证
    validateLoginCaptcha(captcha) {
      if (!captcha) {
        this.loginErrors.captcha = '请输入验证码'
        return false
      }
      
      // 检查验证码是否正确
      if (captcha.toLowerCase() !== this.captchaCode.toLowerCase()) {
        this.loginErrors.captcha = '验证码错误'
        return false
      }

      this.loginErrors.captcha = ''
      return true
    },

    // 注册用户名验证
    validateRegisterUsername(username) {
      if (!username) {
        this.registerErrors.username = '请输入用户名'
        return false
      }

      if (username.length < 3) {
        this.registerErrors.username = '用户名长度至少为3个字符'
        return false
      }

      this.registerErrors.username = ''
      return true
    },

    // 注册邮箱验证
    validateRegisterEmail(email) {
      if (!email) {
        this.registerErrors.email = '请输入邮箱地址'
        return false
      }

      const emailRegex = /^([a-zA-Z0-9]+[-_.]?)+@[a-zA-Z0-9]+.[a-z]+$/
      if (!emailRegex.test(email)) {
        this.registerErrors.email = '请输入有效的邮箱地址'
        return false
      }

      this.registerErrors.email = ''
      return true
    },

    // 注册密码验证
    validateRegisterPassword(password) {
      if (!password) {
        this.registerErrors.password = '请输入密码'
        return false
      }

      if (password.length < 8) {
        this.registerErrors.password = '密码长度至少为8个字符'
        return false
      }
      
      if (!/[A-Za-z]/.test(password) || !/\d/.test(password)) {
        this.registerErrors.password = '密码需包含字母和数字'
        return false
      }

      this.registerErrors.password = ''
      return true
    },

    // 注册确认密码验证
    validateRegisterConfirmPassword(confirmPassword) {
      if (!confirmPassword) {
        this.registerErrors.confirmPassword = '请确认密码'
        return false
      }

      if (this.registerFormData.password !== confirmPassword) {
        this.registerErrors.confirmPassword = '两次输入的密码不一致'
        return false
      }

      this.registerErrors.confirmPassword = ''
      return true
    },

    // 登录处理
    handleLogin(formData) {
      // 清空之前的错误信息
      this.formErrorMessage = '';
      
      // 更新登录表单数据
      this.loginFormData = { ...formData }
      
      // 验证所有字段
      const isEmailValid = this.validateLoginEmail(formData.email)
      const isPasswordValid = this.validateLoginPassword(formData.password)
      const isCaptchaValid = this.validateLoginCaptcha(formData.captcha)

      if (isEmailValid && isPasswordValid && isCaptchaValid) {
        // 调用登录API
        LogAndRes.login(this.hashLoginPassword({...formData})).then(res => {
          if(res.data==="ok"){
            this.$message({
              type: 'success',
              message:'登录成功！'
            })
            this.$router.push('/ai-assistant');
          }
          else{
            this.formErrorMessage = "登录失败！";
          }
        }).catch(error => {
          // 根据后端返回的错误信息显示具体错误
          if (error.response && error.response.data) {
            const errorData = error.response.data;
            if (errorData.email) {
              this.loginErrors.email = errorData.email[0];
            }
            if (errorData.password) {
              this.loginErrors.password = errorData.password[0];
            }
            if (errorData.captcha) {
              this.loginErrors.captcha = errorData.captcha[0];
            }
            if (errorData.detail) {
              this.formErrorMessage = errorData.detail;
            } else if (!errorData.email && !errorData.password && !errorData.captcha) {
              // 如果没有特定字段错误，显示通用错误信息
              this.formErrorMessage = "登录失败：" + (errorData.message || "未知错误");
            }
          } else {
            this.formErrorMessage = "登录失败：网络错误或服务器无响应";
          }
        });
      }
    },

    // 注册处理
    handleRegister(formData) {
      // 清空之前的错误信息
      this.formErrorMessage = '';
      
      // 更新注册表单数据
      this.registerFormData = { ...formData }
      
      // 验证所有字段
      const isUsernameValid = this.validateRegisterUsername(formData.username)
      const isEmailValid = this.validateRegisterEmail(formData.email)
      const isPasswordValid = this.validateRegisterPassword(formData.password)
      const isConfirmPasswordValid = this.validateRegisterConfirmPassword(formData.confirmPassword)

      if (isUsernameValid && isEmailValid && isPasswordValid && isConfirmPasswordValid) {
        // 调用注册API
        LogAndRes.register(this.hashRegisterPassword({...formData})).then(res=>{
          if(res.data==="ok"){
            this.$message({
              type: 'success',
              message:'注册成功，请登录!'
            });
            this.activeForm = 'login';
            // 注册成功后重新生成验证码
            this.generateCaptcha();
          }
          else{
            this.formErrorMessage = "注册失败！";
          }
        }).catch(error => {
          // 根据后端返回的错误信息显示具体错误
          if (error.response && error.response.data) {
            const errorData = error.response.data;
            if (errorData.username) {
              this.registerErrors.username = errorData.username[0];
            }
            if (errorData.email) {
              this.registerErrors.email = errorData.email[0];
            }
            if (errorData.password) {
              this.registerErrors.password = errorData.password[0];
            }
            if (errorData.confirmPassword) {
              this.registerErrors.confirmPassword = errorData.confirmPassword[0];
            }
            if (errorData.detail) {
              this.formErrorMessage = errorData.detail;
            } else if (!errorData.username && !errorData.email && 
                       !errorData.password && !errorData.confirmPassword) {
              // 如果没有特定字段错误，显示通用错误信息
              this.formErrorMessage = "注册失败：" + (errorData.message || "未知错误");
            }
          } else {
            this.formErrorMessage = "注册失败：网络错误或服务器无响应";
          }
        });
      }
    },

    // 登录密码哈希处理
    hashLoginPassword(formData) {
      formData.password = CryptoJS.SHA256(formData.password).toString()
      return formData
    },
    
    // 注册密码哈希处理
    hashRegisterPassword(formData) {
      formData.password = CryptoJS.SHA256(formData.password).toString()
      return formData
    }
  }
}
</script>

<style scoped lang="css" src="@/assets/styles/login.css">
</style>

<style scoped>
.form-error-message {
  color: #e74c3c;
  background-color: #ffeaea;
  border: 1px solid #f5c6cb;
  border-radius: 8px;
  padding: 12px 15px;
  margin-bottom: 20px;
  font-size: 0.9rem;
}
</style>
